import bg.cookbook.ImageHolder;
import bg.cookbook.Util;
import bg.cookbook.model.ImageDataModel;

import com.adobe.webapis.flickr.Photo;
import com.roguedevelopment.objecthandles.Flex4ChildManager;
import com.roguedevelopment.objecthandles.Flex4HandleFactory;
import com.roguedevelopment.objecthandles.ObjectHandles;
import com.roguedevelopment.objecthandles.decorators.AlignmentDecorator;
import com.roguedevelopment.objecthandles.decorators.DecoratorManager;

import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.geom.Point;
import flash.ui.Keyboard;

import mx.events.DragEvent;
import mx.events.FlexEvent;
import mx.managers.DragManager;

protected var objectHandles:ObjectHandles;
protected var decoratorManager:DecoratorManager;
public function addImg(url:String, x:int, y:int):void
{
	var fmodel:ImageDataModel = new ImageDataModel();
	var fimg:ImageHolder = new ImageHolder();
	fmodel.x = x;
	fmodel.y = y;
	fmodel.width = 100;
	fmodel.height = 100;
	fmodel.imageURL=url;
	fimg.model=fmodel;
	fmodel.imgHolder = fimg;
	objectHandles.registerComponent(fmodel, fimg );
	this.addElement(fimg);
}
private function dragDropEnd(event:DragEvent):void
{
	var data:Object = event.dragSource.dataForFormat('items');
	var pt:Point= new Point(this.mouseX,this.mouseY);
	{
		var p:Photo=data[0];
		var photoUrl:String = Util.createUrl(p.server.toString(),p.id.toString(),p.secret,p.farmId.toString());
		addImg(photoUrl,pt.x,pt.y);
	}
}
private function dragEnterEnd(event:DragEvent):void
{
	if (event.dragSource.hasFormat('items'))
	{
		var dropTarget:SlideCreator = event.currentTarget as SlideCreator;
		DragManager.acceptDragDrop(dropTarget);
	}
}
public function previewMode():void
{
	objectHandles.selectionManager.clearSelection();
	m.alpha=0;
}
public function editMode():void
{
	m.alpha=0.7;
}
override protected function initializationComplete() : void
{				
	objectHandles = new ObjectHandles( this , 
		null, 
		new Flex4HandleFactory() , 
		new Flex4ChildManager() );
	
	super.initializationComplete();
	
	decoratorManager = new DecoratorManager( objectHandles, drawingLayer );
	decoratorManager.addDecorator( new AlignmentDecorator() );
}

protected function group1_creationCompleteHandler(event:FlexEvent):void
{
	
	this.addEventListener(KeyboardEvent.KEY_DOWN,function (event:KeyboardEvent):void {
		if(event.keyCode == Keyboard.DELETE)
		{
			var ar:Array = objectHandles.selectionManager.currentlySelected;
			if(ar) 
			{
				for(var i:int=0; i<ar.length;i++)
				{
					var el:ImageHolder = ImageHolder(ar[i].imgHolder);
					objectHandles.unregisterComponent(el);
					this.removeElement(el);
				}
			}
		}
	},false,0,true);
}


protected function group1_clickHandler(event:MouseEvent):void
{
	if(event.target is ImageHolder) return;
	objectHandles.selectionManager.clearSelection();
}